<template>
  <div class="box">
    <TopSearch
      @searchHeader="searchHeader"
      @delsHeader="delsHeader"
      @addHeader="addHeader"
      :control="control"
      :controlPosition="controlPosition"
      :positionName="positionName"
      :disabled="disabled"
      :delsable="delsable"
      :searchConfig="setFormConfig"
    >
     <template #add ><el-button @click="addHeader" v-permission="'products/create'" color="#50BC58"  icon="Plus" circle class="ml-4 button"></el-button></template>
    </TopSearch>
    <ProTable
      class="protable"
      :data="tableData"
      :page="page"
      :column="column"
      :rowControl="rowControl"
      :elProps="elProps"
      :disabled="disabled"
      :controlWidth="controlWidth"
      @row-control-click="onRowControlClick"
      @selection-change="onSelectionChange"
      @page-change="onPageChange"
      @pageRefresh="pageRefresh"
    >
      <template #default="{ row, propname }">
        <div v-if="propname === 'cate' || propname === 'pp' || propname === 'dw' ">
            {{row[propname] && row[propname].name ? row[propname].name : row[propname]}}
        </div>
      </template>
         <template #search_operate>
            <el-table-column  fixed="right" min-width="200px" label="操作">
              <template #default="scope" >
                <div class="flex justify-around">
                <el-link v-permission="'products/update'"  @click="onRowControlClick(scope.row, 'rowedit')" type="primary" :underline="false" >查看</el-link >
                <el-link v-permission="'products/delete'"  @click="onRowControlClick(scope.row, 'rowdel')" type="primary" :underline="false" >刪除</el-link >
                <el-link @click="onRowControlClick(scope.row, 'rowcombination')" type="primary" :underline="false" >查看組合</el-link >
                </div>
              </template>
            </el-table-column>
        </template>
    </ProTable>
          <addEdit ref="AddEditref" :echo="echo" 
          :producttypeList="producttypeList"
          :brandList="brandList"
          :supplierList="supplierList"
          :unitList="unitList"
          @addConfirm="addConfirm"
          ></addEdit>
      <FouDialog
      :title="'產品組合'"
      :width="'50%'"
      v-model:dialogValue="combinationDialog"
    >
      <template #content>
      <ProTable
      :data="combinationList"
      :column="combinationcolumn"
      :elProps="{
        indexType:true
      }"
       :page="[]"
      :rowControl="[]"
      :disabled="[]"
      :controlWidth="[]"
    >
    </ProTable>
      </template>
    </FouDialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import { elProps, controlWidth } from "./index.js";
import { setFormConfig } from "./formConfig";
import addEdit from "./addEdit/index.vue";
import { productgroup,delProductgroup,producttype,brand,supplier,unit } from "@/http/index.js";
import { loading, closeLoading,messageBox,message } from "@/common/function.js";

const echo = ref({});

// 添加編輯彈窗
const AddEditref = ref('');
// 分页数据（不给就没有分页）
const page = reactive({
  current_page: 1, //当前页
  per_page: 10, //每页条数
  total: 10, //总条数
  page_size: [10, 20, 30], //可选分页条数
});
// 字段名对应表头
const column = {
  statuss:'狀態',
  name: "產品名稱",
  number: "產品編號",
  cate:'產品類別',
  dw:'產品單位',
  pp:'產品品牌',
  price:"價格",
  discountprice:'產品折扣價',
  barcode:'條形碼',
  digest:'摘要',
  remark: "備註",
  create_time: "發佈時間",
};
// 表格顶部操作按钮
const control = ["search", "dels"];
const controlPosition = [];
const positionName = ref("");

// 未选中数据是 禁用项
const disabled = ["dels"];
const delsable = ref(true);

const searchHeader = (e, type) => {
  Object.assign(obj, e);
  tableList();
};

const dialogValue = ref(false);

const addHeader = async() => {
  AddEditref.value.dialogValue = true
  AddEditref.value.buttonType = "add"
echo.value = {
    name: "",
    products_type_id: "",//產品分類
    brand_id:'',         //產品品牌
    unit_id:'',          //單位
    barcode: "",
    price: "",
    digest:'',
    remark:'',
    status: "",
    product_item:[],
    discountstatus:false,
}
  dialogValue.value = true;
      await  producttypeSelect()
      await  brandSelect()
      await  supplierSelect()
      await  unitSelect()
};

// 表格行内操作按钮
const rowControl = ["rowedit", "rowdel","rowcombination"];
const combinationDialog = ref(false)
const combinationList = ref([])
const combinationcolumn = {
  name:'產品名字',
  price:'價格',
  status:'狀態',
}
/**表格行内操作
 * @row {object} 行内数据
 * @type {string} 点击按钮类型
 */

const onRowControlClick = async (row, type) => {
  console.log(row,type);
  if (type == "rowedit") {
    const { id, name, products_type_id, brand_id, unit_id, barcode,price,digest,remark,status,discountstatus,starttime,endtime,discountprice,product_item } = row;
    echo.value ={ id, name, products_type_id, brand_id, unit_id, barcode,price,digest,remark,status,discountstatus,discountprice,product_item } 

    if (echo.value.discountstatus ==1) {
      echo.value.discountstatus = true
      echo.value.discounttime = []
      echo.value.discounttime.push(starttime)
      echo.value.discounttime.push(endtime)
    }else{  echo.value.discountstatus = false }


   AddEditref.value.buttonType = "edit"
    AddEditref.value.dialogValue = true;
      await  producttypeSelect()
      await  brandSelect()
      await  supplierSelect()
      await  unitSelect()
  }
  if (type == 'rowdel') {
        messageBox().then(async () => {
        await delTableList(row.id) 
    })
  }
  if (type == 'rowcombination') {
    row.product_item.map(e=>e.status == 1 ?e.status ='發售中' :e.status ='停售')
    combinationList.value = row.product_item
    combinationDialog.value = true
    console.log(row.product_item);
  }
}

// 刪除產品
const delTableList = async (id)=>{
  const data = await delProductgroup(id)
  if (data.code == 200) {
    tableList()
    message('成功刪除產品組合')
  }else{
    message('刪除產品組合失敗','warning')
  }
}
/** 多选
 * @selected {Array} 被选中的行
 */
const ids = ref('')
const onSelectionChange = (e) => {
  let row_id = []
  e.forEach(e => {
    row_id.push(e.id)
  });
  ids.value = row_id.toString()
  delsable.value = e.length === 0;
};

const delsHeader = () => {
    messageBox().then(async () => {
        await delTableList(ids.value) 
    })
};
/**
 * @e {number} 分页操作后的值（当前页|改变后的每页条数）
 * @type {string} <current|size> 分页操作类型（当前页改变|每页条数改变）
 */
const onPageChange = ({ e, type }) => {
  console.log(e, type);
  if (type == "current") {
    obj.page = e;
  }
  if (type == "size") {
     obj.page = 1
    obj.limit = e;
  }
  tableList()
};
const tableData = ref([])
const obj = reactive({
  // school_id:localStorage.getItem('school_id'),
  page: page.current_page,
  limit: page.per_page,
  name: "",
  status: "",
  time: "",
});
const tableList = async ()=>{
  loading()
  const data = await productgroup(obj)
  if (data.code == 200) {
    data.data.data.map(e=>e.status == 1 ?  e.statuss = '發售中' :    e.statuss = '停售')
    tableData.value = data.data.data
    page.current_page = data.data.current_page
    page.per_page = data.data.per_page
    page.total = data.data.total
    console.log( tableData.value);
  }
  closeLoading()
}
const producttypeList = ref([])
const brandList = ref([])
const supplierList = ref([])
const unitList = ref([])
const objs = {limit:100}
const producttypeSelect = async ()=>{
    const data = await producttype(objs)
    if (data.code == 200) {
     producttypeList.value = data.data.data
    }
}
const brandSelect = async ()=>{
    const data = await brand(objs)
       if (data.code == 200) {
     brandList.value = data.data.data
    }
}
const supplierSelect = async ()=>{
    const data = await supplier(objs)
        if (data.code == 200) {
     supplierList.value = data.data.data
    }
}
const unitSelect = async ()=>{
    const data = await unit(objs)
        if (data.code == 200) {
     unitList.value = data.data.data
    }
}

const pageRefresh = async () => {
  await tableList();
};
const addConfirm = ()=>{
    tableList();
}
onMounted(() => {
  tableList();
});

</script>

<style lang="less" scoped>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.box {
  padding: 16px 33px;
}
.button{
  color: #fff;
}
</style>